package com.fjnu.aspect;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 1. 给所有DAO方法新增执行时间日志功能: Around
 * 2. 记录DAO中的所有方法的执行开始时间的日志 Before
 *   PR  homework_3 分支
 * 3. todo:记录DAO中的所有方法的执行结束时间日志  After
 * 4. todo: 记录DAO中的所有delete方法的执行开始时间日志  Before
 *      step1:定义 pointcut: execution(public * com.fjnu.dao.*.delete*(..))
 *      step2: 定义advice
 *      step3: 编写测试方法
 *
 *
 */

@Component
@Aspect
@Order(2)
public class DemoAspect {

    /**
     * part one:  jointpoint
     */

    /**
     * dayLayer() = "execution(public * com.fjnu.dao.*.*(..))"
     */
    @Pointcut("execution(public * com.fjnu.dao..*.*(..))")
    public void daoLayer() {
        /**
         * empty method
         */
    }


    /**
     * Part two: Advice
     */

    @Before("daoLayer()")
    public void beforeExecutionAdvice(JoinPoint jpoint) throws Exception {

        /**
         *  enhacing logic before joinpoint execution
         *
         */
        String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date()) ;
        System.out.println("[INFO] [BeforeAdvice] the method:"
                + jpoint.getSignature().getName() + " was called at" + startTime) ;


    }


    @Around("daoLayer()")
    public Object performanceLogAdvice(ProceedingJoinPoint pjointpoint)
            throws Throwable {

        // add enhanced logic before method execution
        long startTime = System.currentTimeMillis() ;
        // pjointpoint  --> for all matched invoked methods.
        Object ret = pjointpoint.proceed() ;
        // add enhanced logic after method execution.
        System.out.println("[INFO] [AroundAdvice] the method: " + pjointpoint.getSignature().getName()
                                        + " was executed for "
                + (System.currentTimeMillis() - startTime) +" ms") ;


        return ret ;

    }





}
